package cn.itsource.ymcc.consumer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.CourseConstants;
import cn.itsource.ymcc.domain.MessageSms;
import cn.itsource.ymcc.mapper.MessageSmsMapper;
import cn.itsource.ymcc.result.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@Slf4j
@Component
//consumerGroup = 定义组
//topic = 主题
//selectorExpression = tag
@RocketMQMessageListener(
        consumerGroup = "CourseConsumer",
        topic = CourseConstants.TOPIC_COURSE_MESSAGE_SMS,
        selectorExpression = CourseConstants.TAGS_COURSE_MESSAGE_SMS
)
public class CourseConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private MessageSmsMapper mapper;
    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            //获取到消息
            byte[] body = messageExt.getBody();
            String s = new String(body, Constants.UTF8);
            MessageSms messageSms = JSON.parseObject(s,MessageSms.class);
            //发送短信
            System.out.println("发送短信:"+messageSms.getPhone()+",标题:"+messageSms.getTitle());
            //保存数据库
            messageSms.setSendTime(new Date());//设置发送时间
            //一定要有逻辑
            mapper.insert(messageSms);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
